package 简单算法;

/**
 * @Author: 胡成
 * @Version: 0.0.1V
 * @Date: 2019-05-16
 * @Description: 合并两个有序升序的整数数组A和B变成一个新的数组。新数组也要有序。
 * 输入: A=[1,2,3,4], B=[2,4,5,6]
 * 输出: [1,2,2,3,4,4,5,6]
 **/
public class 合并排序数组II {
    public static void main(String[] args) {
        int[] c = mergeSortedArray(new int[]{1, 2, 3, 4}, new int[]{2, 4, 5, 6});
        for (int i = 0; i < c.length; i++) {
            System.out.println(c[i]);
        }
    }

    public static int[] mergeSortedArray(int[] A, int[] B) {
        // write your code here
        int[] c = new int[A.length + B.length];
        int index = 0, i = 0, j = 0;
        //第一个循环是将数组B小于数组A的元素移动新数组C
        while (i < A.length && j < B.length) {
            if (A[i] > B[j]) {
                c[index++] = B[j++];
            } else {
                c[index++] = A[i++];
            }
        }
        while (i < A.length) {
            c[index++] = A[i++];
        }

        while (j < B.length) {
            c[index++] = B[j++];
        }
        return c;
    }
}
